package wiki.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import wiki.generic.utilities.AlreadyExistingElementException;
import wiki.setup.Setup;
/**
 * 
 * @author <p><strong>JwTeam</strong></p> 
 * Responsabile dell'aggiunta di nuove pagine
 */
public class NewPageServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession ses=req.getSession(false);
		if(ses!=null){
			boolean isDoc = (Boolean) ses.getAttribute("rights");
			if(isDoc){
		String corso=(String) ses.getAttribute("corso");
		String newPage=req.getParameter("titolo");
		if(newPage!=null){
			newPage=newPage.replace(" ", "_");
			newPage=Setup.getSetup().getMediator().getGpService().changeInputText(newPage);
			String file="pages/"+newPage+".txt";
			try {
				Setup.getSetup().getMediator().getpService().createNewPage(corso,newPage, file);
				resp.sendRedirect("./view?page="+newPage);
			} catch (AlreadyExistingElementException e) {
				resp.sendRedirect("./html/errorpages/nomepagina.html");
			}
		}
			} else{
				resp.sendRedirect("./html/errorpages/nopermessi.html");
				return;
			}
		} else {
				resp.sendRedirect("./html/LOGIN/login.html");
				return;
		}
		
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.sendRedirect("./html/errorpages/nopermessi.html");
		
	}
	
	
}
